<template>
  <div>
    <el-switch
      v-model="draggable"
      active-text="开启拖拽"
      inactive-text="关闭拖拽"
    ></el-switch>
    <el-button v-if="draggable" @click="batchSave">批量保存</el-button>
    <el-button type="danger" @click="batchDelete">批量删除</el-button>
    <el-tree
      :data="data"
      :props="defaultProps"
      :expand-on-click-node="false"
      show-checkbox
      node-key="catId"
      :default-expanded-keys="expandedKey"
      @node-drop="handleDrop"
      :draggable="draggable"
      :allow-drop="allowDrop"
      ref="menuTree"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            v-if="node.level <= 2"
            type="text"
            size="mini"
            @click="() => append(data)"
          >
            添加
          </el-button>
          <el-button type="text" size="mini" @click="() => update(data)">
            修改
          </el-button>
          <el-button
            v-if="node.childNodes.length == 0"
            type="text"
            size="mini"
            @click="() => remove(node, data)"
          >
            删除
          </el-button>
        </span>
      </span>
    </el-tree>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="close"
    >
      <el-form :model="category">
        <el-form-item label="分类名称">
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图标">
          <el-input v-model="category.icon" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="计量单位">
          <el-input
            v-model="category.productUnit"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="close()">取 消</el-button>
        <el-button type="primary" @click="submit()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      pid: [],
      draggable: false,
      updateNodes: [],
      maxLevel: 1,
      title: "",
      dialogVisible: false, //添加弹框
      expandedKey: [], //需要展开的节点id
      data: [], //数据
      defaultProps: {
        children: "children",
        label: "name",
      },
      //用于添加数据对象
      category: {
        id: "",
        name: "",
        parentCid: 0,
        catLevel: 0,
        showStatus: 1,
        sort: 0,
        productUnit: "",
        icon: "",
      },
    };
  },

  created() {
    this.getMenus();
  },

  methods: {
    // 获取数据列表
    getMenus() {
      this.$http({
        url: this.$http.adornUrl("/product/category/list/tree"),
        method: "get",
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.data = data.categoryTree;
        } else {
          this.dataList = [];
          this.totalPage = 0;
        }
      });
    },

    batchDelete() {
      let catIds = [];
      let checkedNodes = this.$refs.menuTree.getCheckedNodes();
      for(let i = 0;i<checkedNodes.length;i++) {
        catIds.push(checkedNodes[i].catId);
      }
      this.$confirm(`此操作将永久删除这些内容, 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "delete",
            data: this.$http.adornData(catIds, false),
          }).then(({ data }) => {
            if (data.code === 0) {
              this.$message({
                type: "success",
                message: "批量删除成功!",
              });
              //刷新
              this.getMenus();
            } else {
              this.$message({
                type: "info",
                message: "批量删除失败!",
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消批量删除",
          });
        });
    },

    //会话框关闭
    close() {
      this.dialogVisible = false;
      this.category = {
        parentCid: 0,
        catLevel: 0,
        showStatus: 1,
        sort: 0,
      };
    },

    //判断是添加还是修改
    submit() {
      if (this.category.id != "") {
        this.edit();
      } else {
        this.addCategory();
      }
    },

    update(data) {
      this.title = "修改分类";
      this.dialogVisible = true;
      //获取最新数据
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: "get",
      }).then(({ data }) => {
        this.category = data.category;
      });
    },

    edit() {
      this.$http({
        url: this.$http.adornUrl("/product/category/update"),
        method: "put",
        data: this.$http.adornData(this.category, false),
      }).then(({ data }) => {
        if (data.code === 0) {
          this.$message({
            type: "success",
            message: "修改成功!",
          });
          this.dialogVisible = false;
          //刷新
          this.getMenus();
          this.expandedKey = [this.category.parentCid];
          this.category = {
            parentCid: 0,
            catLevel: 0,
            showStatus: 1,
            sort: 0,
          };
        } else {
          this.$message({
            type: "info",
            message: "修改失败!",
          });
        }
      });
    },

    //弹出添加对话框
    append(data) {
      this.title = "添加分类";
      this.dialogVisible = true;
      this.category.parentCid = data.catId;
      this.category.catLevel = data.catLevel * 1 + 1;
    },

    addCategory() {
      this.$http({
        url: this.$http.adornUrl("/product/category/save"),
        method: "post",
        data: this.$http.adornData(this.category, false),
      }).then(({ data }) => {
        if (data.code === 0) {
          this.$message({
            type: "success",
            message: "添加成功!",
          });
          this.dialogVisible = false;
          //刷新
          this.getMenus();
          this.expandedKey = [this.category.parentCid];
          this.category = {
            parentCid: 0,
            catLevel: 0,
            showStatus: 1,
            sort: 0,
          };
        } else {
          this.$message({
            type: "info",
            message: "添加失败!",
          });
        }
      });
    },

    remove(node, data) {
      this.$confirm(`此操作将永久删除[${data.name}], 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var ids = [data.catId];
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "delete",
            data: this.$http.adornData(ids, false),
          }).then(({ data }) => {
            if (data.code === 0) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              //刷新
              this.getMenus();
              this.expandedKey = [node.parent.data.catId];
            } else {
              this.$message({
                type: "info",
                message: "删除失败!",
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    //允许拖拽放值
    allowDrop(draggingNode, dropNode, type) {
      //1.被拖动的当前节点以及所在节点的总层数不能大于3

      //被拖动当前节点总层数
      this.countNodeLevel(draggingNode);
      //abs取绝对值
      let deep = Math.abs(this.maxLevel - draggingNode.level) + 1;
      this.maxLevel = 1; //恢复默认值

      if (type == "inner") {
        //放到里面
        return deep + dropNode.level <= 3;
      } else {
        //放到前面或后面
        return deep + dropNode.parent.level <= 3;
      }
    },

    countNodeLevel(node) {
      //2.找到所有子节点，求出最大深度
      if (node.childNodes != null && node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          if (node.childNodes[i].level > this.maxLevel) {
            this.maxLevel = node.childNodes[i].level;
          }
          this.countNodeLevel(node.childNodes[i]);
        }
      } else {
        //没有子节点则赋值当前节点深度
        this.maxLevel = node.level;
      }
    },

    handleDrop(draggingNode, dropNode, dropType, ev) {
      //1.当前节点最新父节点
      let pCid = 0;
      let siblings = null; //当前节点和目标位置兄弟节点
      if (dropType == "inner") {
        pCid = dropNode.data.catId;
        siblings = dropNode.childNodes;
      } else {
        pCid =
          dropNode.parent.data.catId == undefined
            ? 0
            : dropNode.parent.data.catId;
        siblings = dropNode.parent.childNodes;
      }

      //2.当前拖拽节点的最新顺序
      for (let i = 0; i < siblings.length; i++) {
        if (siblings[i].data.catId == draggingNode.data.catId) {
          //如果遍历的是当前正在拖拽的节点
          let catLevel = draggingNode.level;
          if (catLevel != siblings[i].level) {
            //3.如果当前层级发生变化，获取当前拖拽节点的最新层级
            catLevel = siblings[i].level;
            //修改子节点的层级
            this.updateChildNodeLevel(siblings[i]);
          }
          this.updateNodes.push({
            catId: siblings[i].data.catId,
            sort: i,
            parentCid: pCid,
            catLevel: catLevel,
          });
        } else {
          this.updateNodes.push({ catId: siblings[i].data.catId, sort: i });
        }

        //设置需要展开菜单
        this.pid.push(pCid);
      }
    },

    updateChildNodeLevel(node) {
      let childNodes = node.childNodes;
      for (let i = 0; i < childNodes.length; i++) {
        this.updateNodes.push({
          catId: childNodes[i].data.catId,
          catLevel: childNodes[i].level,
        });
        //递归修改其子节点
        this.updateChildNodeLevel(childNodes[i]);
      }
    },

    //批量保存
    batchSave() {
      //发送请求
      this.$http({
        url: this.$http.adornUrl("/product/category/update/sort"),
        method: "put",
        data: this.$http.adornData(this.updateNodes, false),
      }).then(({ data }) => {
        if (data.code === 0) {
          this.$message({
            type: "success",
            message: "菜单拖拽成功!",
          });
        } else {
          this.$message({
            type: "info",
            message: "菜单拖拽失败!",
          });
        }
        //刷新出新菜单
        this.getMenus();
        //恢复默认值
        this.updateNodes = [];
        this.expandedKey = this.pid;
        this.pid = [];//清空拓展id
      });
    },
  },
};
</script>

<style>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  /* justify-content: space-between; */
  font-size: 14px;
  padding-right: 8px;
}
</style>